package excel

import (
	"fmt"
	"log"

	"github.com/xuri/excelize/v2"
)

type Excel struct {
	FileObj *excelize.File
}

func NewExcel(FilePath string) *Excel {
	e := &Excel{}
	e.Open(FilePath)
	return e
}

func (e *Excel) Open(FilePath string) {
	if f, err := excelize.OpenFile(FilePath); err != nil {
		log.Panic(fmt.Sprintf("无法打开文件[%v]，原因：", FilePath), err)
		return
	} else {
		e.FileObj = f
	}
}

func (e *Excel) NewFile() {
	e.FileObj = excelize.NewFile()
}

func (e *Excel) Close() error {
	return e.FileObj.Close()
}

func (e *Excel) GetSheetList() []string {
	return e.FileObj.GetSheetList()
}

type Filter struct {
	Sheet  string
	Limit  int
	Column []string `json:"column"` // 不指定就显示所有的列
}

func (e *Excel) GetSheetData(filter Filter) ([][]string, error) {
	SheetData, err := e.FileObj.GetRows(filter.Sheet)
	if err != nil {
		return SheetData, err
	}

	// 如果指定了列，则筛选列
	if len(filter.Column) > 0 {
		SheetData = e.filterColumns(SheetData, filter.Column)
	}

	if filter.Limit == 0 {
		return SheetData, nil
	} else if filter.Limit > 0 && filter.Limit < len(SheetData) {
		return SheetData[:filter.Limit], nil
	} else {
		return SheetData, nil
	}
}

// filterColumns 根据列名筛选数据
func (e *Excel) filterColumns(data [][]string, columns []string) [][]string {
	if len(data) == 0 {
		return data
	}

	// 获取表头
	header := data[0]

	// 查找列索引
	columnIndices := make([]int, 0)
	for _, col := range columns {
		for i, h := range header {
			if h == col {
				columnIndices = append(columnIndices, i)
				break
			}
		}
	}

	// 如果没有找到匹配的列，返回空数据
	if len(columnIndices) == 0 {
		return [][]string{}
	}

	// 根据列索引筛选数据
	filteredData := make([][]string, len(data))
	for i, row := range data {
		newRow := make([]string, len(columnIndices))
		for j, colIdx := range columnIndices {
			if colIdx < len(row) {
				newRow[j] = row[colIdx]
			} else {
				newRow[j] = ""
			}
		}
		filteredData[i] = newRow
	}

	return filteredData
}
